<template>
  <div class="navigation-container">
    <!-- 左侧标签区域 -->
    <div class="left-tags">
      <div
        v-for="item in leftValue"
        :key="item.value"
        class="tag-item"
        :class="{ active: selectTag === item.value }"
        @click="handleTagClick(item)"
      >
        <div class="tag-content">
          <Icon :icon="getTagIcon(item.value)" class="tag-icon" />
          <span class="tag-title">{{ item.label }}</span>
        </div>
        <div class="tag-badge" v-if="item.children && item.children.length > 0">
          {{ item.children.length }}
        </div>
      </div>
    </div>

    <!-- 右侧子项区域 -->
    <div class="right-children">
      <div class="children-header">
        <div class="header-info">
          <Icon :icon="getTagIcon(selectTag)" class="header-icon" />
          <span class="header-title">{{ getCurrentTagLabel() }}</span>
        </div>
        <Icon
          icon="ep:plus"
          class="add-btn"
          @click="addNewConversation(selectTag)"
          title="新建对话"
        />
      </div>

      <div class="children-list">
        <div
          v-for="(child, index) in getCurrentChildren()"
          :key="child.uuid"
          class="child-item"
          :class="{ selected: selectedChild === child.uuid }"
          @click="selectChild(child)"
        >
          <div class="child-main">
            <div class="child-info">
              <div class="child-time">{{ formatTime(child.timer) }}</div>
              <div class="child-preview">
                {{ getConversationPreview(child.content, child.type) }}
              </div>
            </div>
            <div class="child-actions">
              <Icon
                icon="ep:delete"
                class="delete-btn"
                v-if="index !== 0"
                @click.stop="deleteChild(selectTag, child.uuid)"
                title="删除"
              />
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="getCurrentChildren().length === 0" class="empty-state">
          <Icon :icon="getTagIcon(selectTag)" class="empty-icon" />
          <p class="empty-text">暂无{{ getCurrentTagLabel() }}</p>
          <el-button type="primary" @click="addNewConversation(selectTag)">
            <Icon icon="ep:plus" />
            新建对话
          </el-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { generateUUID } from '@/utils'
import { initDb, getAiMessagesByType, addAiMessage, delAiMessage } from '@/db/index.js'
import { emitter } from '@/utils/eventBus.ts'

const props = defineProps({
  selectedChild: [String, Number]
})

const selectTag = ref('ai')
const leftValue = ref([
  {
    label: 'AI创建数字员工任务',
    value: 'ai',
    children: []
  },
  {
    label: '手动创建数字员工任务',
    value: 'manual',
    children: []
  },
  {
    label: 'AI大模型',
    value: 'largeModel',
    children: []
  }
])

const emit = defineEmits(['setSelectTag', 'selectChild', 'deleteChild', 'addConversation'])

// 获取标签图标
const getTagIcon = (value) => {
  const iconMap = {
    ai: 'ep:cpu',
    manual: 'ep:edit-pen',
    largeModel: 'ep:chat-dot-round'
  }
  return iconMap[value] || 'ep:document'
}

// 获取当前标签名称
const getCurrentTagLabel = () => {
  const currentTag = leftValue.value.find((item) => item.value === selectTag.value)
  return currentTag ? currentTag.label : ''
}

// 获取当前选中标签的子项
const getCurrentChildren = () => {
  const currentTag = leftValue.value.find((item) => item.value === selectTag.value)
  return currentTag ? currentTag.children : []
}

// 格式化时间显示
const formatTime = (timestamp) => {
  if (!timestamp) return '未知时间'
  const date = new Date(timestamp)
  return date.toLocaleString('zh-CN', {
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 获取对话预览
const getConversationPreview = (content, type) => {
  if (!content || content === '[]') return '暂无内容'

  try {
    const parsedContent = JSON.parse(content)

    // 如果是大模型类型，显示URL信息
    if (type === 'largeModel') {
      if (parsedContent && parsedContent.url) {
        return `已配置: ${parsedContent.url.substring(0, 30)}...`
      } else {
        return '未配置URL'
      }
    }

    // 其他类型显示消息预览
    if (Array.isArray(parsedContent) && parsedContent.length > 0) {
      const lastUserMessage = parsedContent.filter((msg) => msg.role === 'user').pop()
      if (lastUserMessage && lastUserMessage.content) {
        return lastUserMessage.content.substring(0, 40) + '...'
      }
      const lastMessage = parsedContent[parsedContent.length - 1]
      if (lastMessage && lastMessage.content) {
        return lastMessage.content.substring(0, 40) + '...'
      }
    }
  } catch (e) {
    return content.substring(0, 40) + '...'
  }
  return '暂无内容'
}

// 初始化数据
const initializeData = async () => {
  try {
    await initDb()

    const aiMessages = await getAiMessagesByType('ai')
    const manualMessages = await getAiMessagesByType('manual')
    const largeModelMessages = await getAiMessagesByType('largeModel')

    // 确保至少有一个对话
    if (aiMessages.length === 0) {
      const newAiConversation = await createNewConversation('ai', {
        role: 'ai',
        content:
          '「输入要创建的任务即可自动创建外呼任务」 - 这是一个基于人工智能的智能外呼任务自动化创建系统，让您只需要用自然语言描述需求，AI就能自动为您生成完整的外呼任务配置。',
        isThinking: false
      })
      leftValue.value[0].children = [newAiConversation]
    } else {
      leftValue.value[0].children = aiMessages
    }

    if (manualMessages.length === 0) {
      const newManualConversation = await createNewConversation('manual', {
        role: 'ai',
        content:
          '「详细描述您的外呼任务需求」 - 为了为您生成最专业、最有效的外呼话术和任务配置，我们需要了解您的具体业务背景和需求细节。',
        isThinking: false
      })
      leftValue.value[1].children = [newManualConversation]
    } else {
      leftValue.value[1].children = manualMessages
    }

    if (largeModelMessages.length === 0) {
      const newLargeModelConversation = await createNewConversation('largeModel', {})
      leftValue.value[2].children = [newLargeModelConversation]
    } else {
      leftValue.value[2].children = largeModelMessages
    }

    // 自动选择第一个AI对话
    if (leftValue.value[0].children.length > 0) {
      const firstChild = leftValue.value[0].children[0]
      emit('selectChild', firstChild)
    }
  } catch (error) {
    console.error('初始化数据失败:', error)
  }
}

// 创建新对话
const createNewConversation = async (type, obj) => {
  const uuid = generateUUID()
  let content

  // 根据类型设置不同的初始内容
  if (type === 'largeModel') {
    content = JSON.stringify({ url: '' }) // 大模型类型存储配置对象
  } else {
    content = JSON.stringify([obj]) // 其他类型存储消息数组
  }

  const newConversation = {
    timer: new Date().getTime(),
    content: content,
    uuid: uuid,
    type: type
  }

  await addAiMessage(newConversation)
  return newConversation
}

// 标签点击事件
const handleTagClick = (item) => {
  selectTag.value = item.value
  emit('setSelectTag', item.value)

  // 如果当前标签有子项，自动选择第一个
  if (item.children && item.children.length > 0) {
    emit('selectChild', item.children[0])
  }
}

// 新建对话
const addNewConversation = async (type) => {
  try {
    let obj
    if (type === 'ai') {
      obj = {
        role: 'ai',
        content:
          '「输入要创建的任务即可自动创建外呼任务」 - 这是一个基于人工智能的智能外呼任务自动化创建系统，让您只需要用自然语言描述需求，AI就能自动为您生成完整的外呼任务配置。',
        isThinking: false
      }
    } else if (type === 'manual') {
      obj = {
        role: 'ai',
        content:
          '「详细描述您的外呼任务需求」 - 为了为您生成最专业、最有效的外呼话术和任务配置，我们需要了解您的具体业务背景和需求细节。',
        isThinking: false
      }
    } else {
      obj = {}
    }

    const newConversation = await createNewConversation(type, obj)

    const parentIndex = leftValue.value.findIndex((item) => item.value === type)
    if (parentIndex !== -1) {
      leftValue.value[parentIndex].children.unshift(newConversation)
      emit('selectChild', newConversation)
      emit('addConversation', newConversation)
    }

    return newConversation
  } catch (error) {
    console.error('新建对话失败:', error)
  }
}

const selectChild = (child) => {
  emit('selectChild', child)
}

const deleteChild = async (parentValue, childUuid) => {
  try {
    await delAiMessage(childUuid)

    const parent = leftValue.value.find((item) => item.value === parentValue)
    if (parent) {
      parent.children = parent.children.filter((child) => child.uuid !== childUuid)
    }

    emit('deleteChild', parentValue, childUuid)
  } catch (error) {
    console.error('删除对话失败:', error)
  }
}

// 更新对话预览
const updateConversationPreview = ({ uuid, messages, type }) => {
  console.log('Navigation: 更新对话预览', uuid, messages, type)
  const allChildren = [
    ...leftValue.value[0].children,
    ...leftValue.value[1].children,
    ...leftValue.value[2].children
  ]
  const targetChild = allChildren.find((child) => child.uuid === uuid)

  if (targetChild) {
    if (type === 'largeModel') {
      // 大模型类型直接存储配置对象
      targetChild.content = JSON.stringify(messages)
    } else {
      // 其他类型存储消息数组
      targetChild.content = JSON.stringify(messages)
    }
    targetChild.timer = new Date().getTime()
  }
}

// 组件挂载
onMounted(() => {
  initializeData()
  // 监听对话预览更新
  emitter.on('updateConversationPreview', updateConversationPreview)
})

onUnmounted(() => {
  emitter.off('updateConversationPreview', updateConversationPreview)
})
</script>

<style scoped>
.navigation-container {
  display: flex;
  height: 100%;
  background: #fafbfc;
  border-radius: 8px;
  overflow: hidden;
}

/* 左侧标签区域 */
.left-tags {
  width: 200px;
  background: linear-gradient(180deg, #f8faff 0%, #f0f7ff 100%);
  border-right: 1px solid #e4e9f2;
  padding: 16px 12px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.tag-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 12px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  background: #ffffff;
  border: 1px solid #e4e9f2;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.tag-item:hover {
  background: linear-gradient(135deg, #0052cc 0%, #003d99 100%);
  color: #ffffff;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 82, 204, 0.3);
  border-color: transparent;
}

.tag-item.active {
  background: linear-gradient(135deg, #0052cc 0%, #003d99 100%);
  color: #ffffff;
  border-color: transparent;
  box-shadow: 0 4px 12px rgba(0, 82, 204, 0.4);
}

.tag-content {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.tag-icon {
  font-size: 16px;
  flex-shrink: 0;
}

.tag-title {
  font-weight: 500;
  font-size: 13px;
  line-height: 1.4;
}

.tag-badge {
  background: rgba(255, 255, 255, 0.2);
  color: inherit;
  padding: 2px 6px;
  border-radius: 10px;
  font-size: 11px;
  font-weight: 500;
  min-width: 18px;
  text-align: center;
}

.tag-item:not(.active) .tag-badge {
  background: #0052cc;
  color: #ffffff;
}

/* 右侧子项区域 */
.right-children {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #ffffff;
}

.children-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f2f5;
  background: linear-gradient(135deg, #f8faff 0%, #f0f7ff 100%);
}

.header-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.header-icon {
  font-size: 18px;
  color: #0052cc;
}

.header-title {
  font-weight: 600;
  font-size: 16px;
  color: #2c3e50;
}

.add-btn {
  font-size: 16px;
  color: #0052cc;
  cursor: pointer;
  padding: 6px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

.add-btn:hover {
  background: rgba(0, 82, 204, 0.1);
  transform: scale(1.1);
}

.children-list {
  flex: 1;
  overflow-y: auto;
  padding: 16px;
}

.child-item {
  margin-bottom: 12px;
  padding: 16px;
  background: #ffffff;
  border: 1px solid #f0f2f5;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  width: 260px;
}

.child-item:hover {
  background: #f8faff;
  border-color: #0052cc;
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 82, 204, 0.15);
}

.child-item.selected {
  background: linear-gradient(135deg, #f0f7ff 0%, #e6f4ff 100%);
  border-color: #0052cc;
  box-shadow: 0 4px 12px rgba(0, 82, 204, 0.2);
}

.child-item.selected::before {
  content: '';
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 4px;
  background: linear-gradient(to bottom, #0052cc 0%, #003d99 100%);
  border-radius: 0 4px 4px 0;
}

.child-main {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.child-info {
  flex: 1;
  min-width: 0;
}

.child-time {
  font-weight: 500;
  font-size: 13px;
  color: #0052cc;
  margin-bottom: 6px;
}

.child-preview {
  font-size: 12px;
  color: #7f8c8d;
  line-height: 1.4;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.child-actions {
  margin-left: 12px;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.child-item:hover .child-actions {
  opacity: 1;
}

.delete-btn {
  font-size: 14px;
  color: #e74c3c;
  cursor: pointer;
  padding: 6px;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.delete-btn:hover {
  background: #ffeaea;
  color: #c0392b;
  transform: scale(1.1);
}

/* 空状态 */
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  text-align: center;
}

.empty-icon {
  font-size: 48px;
  color: #bdc3c7;
  margin-bottom: 16px;
}

.empty-text {
  font-size: 16px;
  color: #7f8c8d;
  margin: 0 0 20px 0;
}

/* 滚动条样式 */
.children-list::-webkit-scrollbar {
  width: 6px;
}

.children-list::-webkit-scrollbar-track {
  background: #f1f3f4;
  border-radius: 3px;
}

.children-list::-webkit-scrollbar-thumb {
  background: linear-gradient(180deg, #c1c9d2 0%, #a8b4c0 100%);
  border-radius: 3px;
  transition: all 0.2s ease;
}

.children-list::-webkit-scrollbar-thumb:hover {
  background: linear-gradient(180deg, #0052cc 0%, #1d4ed8 100%);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .left-tags {
    width: 160px;
    padding: 12px 8px;
  }

  .tag-item {
    padding: 12px 8px;
  }

  .tag-title {
    font-size: 12px;
  }

  .children-header {
    padding: 12px 16px;
  }

  .header-title {
    font-size: 14px;
  }

  .children-list {
    padding: 12px;
  }

  .child-item {
    padding: 12px;
  }
}
</style>
